package org.jiuling.network.tools.http.request.interfaces;

import com.alibaba.fastjson2.JSON;
import org.jiuling.local.tools.exception.LocalToolsException;
import org.jiuling.local.tools.verify.StringVerify;
import org.jiuling.network.tools.http.request.HttpRequest;
import org.jiuling.network.tools.http.request.enums.RequestMethodEnum;
import org.jiuling.network.tools.http.request.exception.RequestException;
import org.jiuling.network.tools.http.request.factory.HttpRequestFactory;
import org.jiuling.network.tools.http.request.interfaces.annotations.Url;
import org.jiuling.network.tools.http.request.model.HttpRequestParam;
import org.jiuling.network.tools.response.ResponseData;
import org.jiuling.network.tools.response.verify.ResponseDataVerify;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * 请求接口
 * @author 紫灵
 * @date 2022年11月22日 09时21分56秒
 */
public interface Request<T> {

    default T send(String path,RequestMethodEnum requestMethodEnum) throws RequestException {
        Class<? extends Request> clazz = this.getClass();
        if(StringVerify.isBlank(path)) {
            Url url = clazz.getAnnotation(Url.class);
            path = url.path();
            if (!StringVerify.isBlank(path)) {
                System.out.println(path);
            }
        }
        HttpRequest httpRequest = new HttpRequest();
        HttpRequestFactory httpRequestFactory = httpRequest.openHttpRequestFactory(path);
        HttpRequestParam httpRequestParam = new HttpRequestParam().add("appKey","4c834543998c4ea88797ae3f776a6c4c").add("appSecret","1a4e3809251bb1e38355503d92f8695e");
        httpRequestFactory.setRequestMethod(requestMethodEnum);
        httpRequestFactory.setRequestParam(httpRequestParam);


        ParameterizedType param = (ParameterizedType) clazz.getGenericInterfaces()[0];
        Type type = param.getActualTypeArguments()[0];
        try {
            return JSON.parseObject(JSON.toJSONString(ResponseDataVerify.verifyAndrReturnData(JSON.parseObject(httpRequest.send().getBody(), ResponseData.class),200)),type);
        } catch (IOException | LocalToolsException | NoSuchAlgorithmException | KeyManagementException e) {
            throw new RequestException(e.getLocalizedMessage());
        }
    }

    default T send(RequestMethodEnum requestMethodEnum) throws RequestException {
        return send(null,requestMethodEnum);
    }

}
